<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\service;

use app\store\model\Coupon as CouponModel;
use app\store\model\UserCoupon as UserCouponModel;
use app\common\service\BaseService;
use cores\exception\BaseException;

/**
 * 优惠券服务类
 * Class Coupon
 * @package app\store\service
 */
class Coupon extends BaseService
{
    /**
     * 批量发放优惠券
     * @param array $data
     * @return bool
     * @throws BaseException
     */
    public function give(array $data): bool
    {
        // 获取优惠券信息
        $couponInfo = CouponModel::detail($data['couponId']);
        // 验证优惠券是否可领取
        $this->checkReceive($couponInfo, $data);
        // 发放给指定的用户
        if ($data['type'] == 10) {
            return $this->receive($couponInfo, $data['target']['userIds']);
        }
        return true;
    }

    /**
     * 执行批量领取优惠券
     * @param CouponModel $couponInfo 优惠券详情
     * @param array $userIds 用户ID集
     * @return bool
     * @throws BaseException
     */
    private function receive(CouponModel $couponInfo, array $userIds): bool
    {
        foreach ($userIds as $userId) {
            // 验证当前用户是否已领取
            if (UserCouponModel::checktUserCoupon($couponInfo['coupon_id'], $userId)) {
                throwError("用户(ID:{$userId}) 已领取该优惠券，不能重复发放");
            }
            // 添加领取记录
            $model = new UserCouponModel;
            $model->add($userId, $couponInfo);
        }
        return true;
    }

    /**
     * 验证优惠券是否可领取
     * @param CouponModel $couponInfo 优惠券详情
     * @param array $data
     * @throws BaseException
     */
    private function checkReceive(CouponModel $couponInfo, array $data)
    {
        // 验证优惠券状态是否可领取
        $model = new CouponModel;
        if (!$model->checkReceive($couponInfo)) {
            throwError($model->getError());
        }
        // 验证优惠券数量是否充足
        $quantity = 0;
        if ($data['type'] == 10) {
            $quantity = count($data['target']['userIds']);
        }
        if ($couponInfo['total_num'] > -1 && ($couponInfo['receive_num'] + $quantity) > $couponInfo['total_num']) {
            throwError('很抱歉，优惠券剩余数量不足 无法发放');
        }
    }
}